<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>设计模式-七大设计原则 | Joey</title><meta name="keywords" content="设计模式,设计原则"><meta name="author" content="方陈勇"><meta name="copyright" content="方陈勇"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="设计模式-七大设计原则">
<meta property="og:type" content="article">
<meta property="og:title" content="设计模式-七大设计原则">
<meta property="og:url" content="http://fangchenyong.top/2020/07/13/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E4%B8%83%E5%A4%A7%E5%8E%9F%E5%88%99/index.html">
<meta property="og:site_name" content="Joey">
<meta property="og:description" content="设计模式-七大设计原则">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/BEF238F4E59CF4D91A694FE9C5DBC030.JPG">
<meta property="article:published_time" content="2020-07-12T16:00:00.000Z">
<meta property="article:modified_time" content="2020-07-14T14:49:01.346Z">
<meta property="article:author" content="方陈勇">
<meta property="article:tag" content="设计模式">
<meta property="article:tag" content="设计原则">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/BEF238F4E59CF4D91A694FE9C5DBC030.JPG"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://fangchenyong.top/2020/07/13/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E4%B8%83%E5%A4%A7%E5%8E%9F%E5%88%99/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2020-07-14 22:49:01'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/3FD9B055-6361-49B7-B8CE-5BA9144BD27F.JPG" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">40</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">47</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">49</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> List</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> Music</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> Movie</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> About</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/BEF238F4E59CF4D91A694FE9C5DBC030.JPG')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Joey</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> List</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> Music</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> Movie</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> About</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">设计模式-七大设计原则</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-07-12T16:00:00.000Z" title="发表于 2020-07-13 00:00:00">2020-07-13</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2020-07-14T14:49:01.346Z" title="更新于 2020-07-14 22:49:01">2020-07-14</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99/">设计原则</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>12分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="设计模式-七大设计原则"><a href="#设计模式-七大设计原则" class="headerlink" title="设计模式-七大设计原则"></a>设计模式-七大设计原则</h1><p>==<strong>三种类型</strong>==</p>
<ol>
<li><strong>创建型模式：单例模式、抽象工厂模式、原型模式、建造者模式、工厂模式</strong></li>
<li><strong>结构性模式：适配器模式、桥接模式、装饰模式、组合模式、外观模式、享元模式、代理模式</strong></li>
<li><strong>行为型模式：模板方法模式、命令模式、访问者模式、迭代器模式、观察者模式、中介者模式、备忘录模式、解释器模式、状态模式、策略模式、职责链模式</strong></li>
</ol>
<p>==<strong>核心思想</strong>==</p>
<ol>
<li><strong>代码重用性（即：相同功能的代码，不用多次编写）</strong></li>
<li><strong>可读性（即：编程规范性，便于其他程序员的阅读和理解）</strong></li>
<li><strong>可扩展性（即：当需要增加新的功能时，非常的方便，称为可维护）</strong></li>
<li><strong>可靠性（即：当我们增加新的功能后，对原来的功能没有影响）</strong></li>
<li><strong>使程序呈现高内聚，低耦合的特性</strong></li>
</ol>
<h2 id="1）、单一职责原则（Single-Responsibility）"><a href="#1）、单一职责原则（Single-Responsibility）" class="headerlink" title="1）、单一职责原则（Single Responsibility）"></a>1）、单一职责原则（Single Responsibility）</h2><p><strong>目的：</strong>降低代码复杂度、系统解耦合、提高可读性</p>
<p>​        对类来说，即一个类应该只负责一项职责。如类A负责两个不同职责：职责1，职责2。当职责1需求变更而改变A时，可能造成职责2执行错误，所以需要将类A的粒度分解为A1，A2。</p>
<ol>
<li>降低类的复杂度，一个类只负责一项职责。</li>
<li>提高类的可读性，可维护性。</li>
<li>降低变更引起的风险。</li>
<li>通常情况下，我们应当遵守单一职责原则，只有逻辑足够简单，才可以在代码级违反单一职责；只有类中方法数量足够少，可以在方法级别保持单一职责原则。</li>
</ol>
<p><strong>==快速记忆：各司其职，降低耦合==</strong></p>
<h2 id="2）、接口隔离原则（Interface-Segregation）"><a href="#2）、接口隔离原则（Interface-Segregation）" class="headerlink" title="2）、接口隔离原则（Interface Segregation）"></a>2）、接口隔离原则（Interface Segregation）</h2><p><strong>目的：</strong>避免接口过于臃肿</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">interface</span> <span class="title">Interface1</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">fun1</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">fun2</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">fun3</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">fun4</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">fun5</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//类A通过Interface1会依赖（使用）类B</span></span><br><span class="line"><span class="comment">//但是A只会用到接口的fun1(),fun2(),fun3()三个方法</span></span><br><span class="line"><span class="comment">//类C通过Interface1会依赖（使用）类D</span></span><br><span class="line"><span class="comment">//但是C只会用到接口的fun1(),fun4(),fun5()三个方法</span></span><br></pre></td></tr></table></figure>

<ol>
<li><p>类A通过Interface1会依赖（使用）类B（<strong>比如：在control层调用service层实现方法时</strong>），类C通过Interface1会依赖（使用）类D，如果接口Interface1对于类A和类C来说不是最小接口，那么类B和类D必须去实现他们不需要的方法。</p>
</li>
<li><p>将接口Interface1拆分为独立的几个接口，类A和类C分别与他们需要的接口建立依赖关系。也就是采用接口隔离原则。</p>
</li>
<li><p>接口Interface1中出现的方法，根据实际情况拆分为三个接口</p>
 <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">interface</span> <span class="title">Interface1</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">fun1</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">interface</span> <span class="title">Interface2</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">fun2</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">fun3</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">interface</span> <span class="title">Interface3</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">fun4</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">fun5</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> <span class="keyword">implements</span> <span class="title">Interface1</span>,<span class="title">Interface2</span></span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">D</span> <span class="keyword">implements</span> <span class="title">Interface1</span>,<span class="title">Interface3</span></span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> <strong>==快速记忆：利用接口的多实现，拆分粒度尽量小，避免实现类重写不需要的方法==</strong></p>
</li>
</ol>
<h2 id="3）、依赖倒转原则（Dependence-Inversion）"><a href="#3）、依赖倒转原则（Dependence-Inversion）" class="headerlink" title="3）、依赖倒转原则（Dependence Inversion）"></a>3）、依赖倒转原则（Dependence Inversion）</h2><p><strong>目的：</strong>避免需求变化导致过多的维护工作</p>
<ol>
<li><p>高层模块不应该依赖低层模块，二者都应该依赖其抽象，低层模块尽量都要有抽象类或接口，或者两者都有，程序稳定性更好。</p>
</li>
<li><p>抽象不应该依赖细节，细节应该依赖抽象。</p>
</li>
<li><p>依赖倒转（倒置）的中心思想是面向接口编程。</p>
</li>
<li><p>依赖倒转原则是基于这样的设计理念：相对于细节的多变性，抽象的东西要稳定的多。以抽象为基础搭建的架构比以细节为基础的架构要稳定的多。在java中，抽象指的是接口或抽象类，细节就是具体的实现类。</p>
</li>
<li><p>使用接口或抽象类的目的是制定好规范，而不涉及任何具体的操作，把展示细节的任务交给他们的实现类去完成。</p>
</li>
<li><p>变量的声明类型尽量是抽象类或接口，这样我们的变量引用和实际对象间，就存在一个缓冲层，利于程序扩展和优化。</p>
</li>
<li><p>继承时遵循里氏替换原则。</p>
 <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DependenceInversion</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Person person = <span class="keyword">new</span> Person();</span><br><span class="line">        person.receive(<span class="keyword">new</span> Email());</span><br><span class="line">        person.receive(<span class="keyword">new</span> WeChat());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">interface</span> <span class="title">Info</span></span>&#123;</span><br><span class="line">    <span class="function">String <span class="title">getInfo</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Email</span> <span class="keyword">implements</span> <span class="title">Info</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getInfo</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Receive Email&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">WeChat</span> <span class="keyword">implements</span> <span class="title">Info</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getInfo</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;Receive WeChat&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//person 接受信息</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">receive</span><span class="params">(Info info)</span> </span>&#123;</span><br><span class="line">        System.out.println(info.getInfo());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> <strong>依赖关系的传递方式：</strong></p>
<ul>
<li>接口传递</li>
<li>构造方法传递</li>
<li>setter方式传递</li>
</ul>
<p> <strong>==快速记忆：面向接口编程，这就是为什么service 要多写个接口，然后才是实现类==</strong></p>
</li>
</ol>
<h2 id="4）、里氏替换原则（Liskov-Substitution）"><a href="#4）、里氏替换原则（Liskov-Substitution）" class="headerlink" title="4）、里氏替换原则（Liskov Substitution）"></a>4）、里氏替换原则（Liskov Substitution）</h2><p><strong>目的：</strong>避免系统继承体系被破坏</p>
<ol>
<li><p>里氏替换原则(Liskov Substitution Principle)在1988年，由麻省理工学院一位姓里的女士提出。</p>
</li>
<li><p>如果对每个类型为T1的对象o1，都有类型为T2的对象o2，使得以T1定义的所有程序P在所有的对象o1都代换成o2时，程序P的行为没有发生变化，那么类型T2是类型T1的子类型。换句话说，所有引用基类的地方必须能透明地使用其子类的对象。</p>
</li>
<li><p>在使用继承时，遵循里氏替换原则，在子类中尽量不要重写父类的方法。</p>
</li>
<li><p>继承实际上让两个类耦合性增强了，给程序带来侵入性。在适当的情况下，可以通过聚合，组合，依赖来解决问题。</p>
</li>
<li><p>继承包含这样一层含义：父类中凡是已经实现好的方法，实际上是在设定规范和契约，虽然它不强制要求所有的子类必须遵循这些契约，但是如果子类对这些已经实现的方法任意修改，就会对整个继承体系造成破坏。</p>
 <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LiskovSubstitution</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        A a = <span class="keyword">new</span> A();</span><br><span class="line">        System.out.println(<span class="string">&quot;2-1=&quot;</span> + a.func1(<span class="number">2</span>, <span class="number">1</span>));</span><br><span class="line"></span><br><span class="line">        B b = <span class="keyword">new</span> B();</span><br><span class="line">        System.out.println(<span class="string">&quot;2+1=&quot;</span> + b.func1(<span class="number">2</span>, <span class="number">1</span>));</span><br><span class="line">        System.out.println(<span class="string">&quot;2+1+9=&quot;</span> + b.func2(<span class="number">2</span>, <span class="number">1</span>));</span><br><span class="line">        System.out.println(<span class="string">&quot;B类使用A类方法：2-1=&quot;</span> + b.func3(<span class="number">2</span>, <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Base</span> </span>&#123;</span><br><span class="line">    <span class="comment">//把基础方法和成员抽取成基类</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">func1</span><span class="params">(<span class="keyword">int</span> num1, <span class="keyword">int</span> num2)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> num1 - num2;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> <span class="keyword">extends</span> <span class="title">Base</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"><span class="comment">//    public int func1(int num1, int num2) &#123;</span></span><br><span class="line"><span class="comment">//        return num1 - num2;</span></span><br><span class="line"><span class="comment">//    &#125;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> <span class="keyword">extends</span> <span class="title">Base</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// TODO 类 B `无意` 重写了父类 A 方法，造成原有方法发生改变。</span></span><br><span class="line"><span class="comment">//    @Override</span></span><br><span class="line"><span class="comment">//    public int func1(int num1, int num2) &#123;</span></span><br><span class="line"><span class="comment">//        return num1 + num2;</span></span><br><span class="line"><span class="comment">//    &#125;</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">func1</span><span class="params">(<span class="keyword">int</span> num1, <span class="keyword">int</span> num2)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> num1 + num2;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">func2</span><span class="params">(<span class="keyword">int</span> num1, <span class="keyword">int</span> num2)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> func1(num1, num2) + <span class="number">9</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> A a = <span class="keyword">new</span> A();<span class="comment">//组合</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//使用 A 方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">func3</span><span class="params">(<span class="keyword">int</span> num1, <span class="keyword">int</span> num2)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.a.func1(num1, num2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> <strong>==快速记忆：子类可以扩展父类的功能，但不能改变父类原有的功能==</strong></p>
</li>
</ol>
<h2 id="5）、开闭原则（Open-Closed）"><a href="#5）、开闭原则（Open-Closed）" class="headerlink" title="5）、开闭原则（Open Closed）"></a>5）、开闭原则（Open Closed）</h2><p><strong>目的：</strong>提高扩展性、便于维护</p>
<ol>
<li><p>开闭原则(Open Closed Principle) 是编程中最基础、最重要的设计原则。</p>
</li>
<li><p>一个软件实体，比如类，模块和函数应该对==提供方扩展开放==，对==使用方修改关闭==。用抽象构建框架，用实现扩展细节。</p>
</li>
<li><p>当软件需要变化时，尽量通过扩展软件实体的行为来实现变化，而不是通过修改已有的代码来实现变化。</p>
</li>
<li><p>编程中遵循其它原则，以及使用设计模式的目的就是遵循开闭原则。</p>
 <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OpenClosed</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Use use = <span class="keyword">new</span> Use();</span><br><span class="line">        use.drawShape(<span class="keyword">new</span> Triangle());</span><br><span class="line">        use.drawShape(<span class="keyword">new</span> Circle());</span><br><span class="line">        use.drawShape(<span class="keyword">new</span> OtherGraphics());<span class="comment">//只需要让 此类继承 抽象类，子类实现具体方法  OCP原则</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Use</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">drawShape</span><span class="params">(Shape shape)</span> </span>&#123;</span><br><span class="line">        shape.draw();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">Shape</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">draw</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Triangle</span> <span class="keyword">extends</span> <span class="title">Shape</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">draw</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;子类实现具体功能：三角形&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Circle</span> <span class="keyword">extends</span> <span class="title">Shape</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">draw</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;子类实现具体功能：圆形&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">OtherGraphics</span> <span class="keyword">extends</span> <span class="title">Shape</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">draw</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;子类实现具体功能：任何形状&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> <strong>==快速记忆：比如你作为开发可以修改程序，但用户无法修改。即 类，模块和函数提供方开放修改，调用方关闭修改==</strong></p>
</li>
</ol>
<h2 id="6）、迪米特法则（Demeter）"><a href="#6）、迪米特法则（Demeter）" class="headerlink" title="6）、迪米特法则（Demeter）"></a>6）、迪米特法则（Demeter）</h2><p><strong>目的：</strong>降低类与类之间的耦合</p>
<ol>
<li><p>一个对象应该对其他对象保持最少的了解（最少知道原则 LKP）。</p>
</li>
<li><p>类与类关系越密切，耦合度越大。要求降低类之间耦合，而不是完全解耦。</p>
</li>
<li><p>迪米特法则(Demeter Principle)，即一个类对自己依赖的类知道的越少越好。也就是说，对于被依赖的类不管多么复杂，都尽量将逻辑封装在类的内部。对外除了提供public方法，不对外泄露任何信息。</p>
</li>
<li><p>迪米特法则更简单的定义：只与直接的朋友通信。</p>
</li>
<li><p>直接的朋友：每个对象都会与其他对象有耦合关系，只要两个对象之间有耦合关系，我们就说这两个对象之间是朋友关系。耦合的方式很多，依赖，关联，组合，聚合 等。其中，我们称出现成员变量，方法参数，方法返回值中的类为直接的朋友，而出现在局部变量中的类不是直接的朋友。也就是说，陌生的类最好不要以局部变量的形式出现在类的内部。</p>
 <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span></span>&#123;</span><br><span class="line">    B b;<span class="comment">//全局变量 - 直接朋友</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> B <span class="title">m1</span><span class="params">()</span></span>&#123;&#125; <span class="comment">//方法返回值 - 直接朋友</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">m2</span><span class="params">(B b)</span></span>&#123;&#125;<span class="comment">//方法入参 - 直接朋友</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">m3</span><span class="params">()</span></span>&#123;</span><br><span class="line">        B b1 = <span class="keyword">new</span> B();<span class="comment">// 局部变量 非直接朋友</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

 <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Demeter</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        SchoolManager schoolManager = <span class="keyword">new</span> SchoolManager();</span><br><span class="line">        schoolManager.printAllEmployee(<span class="keyword">new</span> CollegeManager());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//学院员工类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CollegeEmployee</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String id;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(String id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//管理学院员工的管理类:</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CollegeManager</span> </span>&#123;</span><br><span class="line">    <span class="comment">//返回学院的所有员工 //TODO CollegeEmployee 直接朋友</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;CollegeEmployee&gt; <span class="title">getAllEmployee</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        List&lt;CollegeEmployee&gt; list = <span class="keyword">new</span> ArrayList&lt;CollegeEmployee&gt;();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123; <span class="comment">//这里我们增加了10 个员工到list ，</span></span><br><span class="line">            CollegeEmployee emp = <span class="keyword">new</span> CollegeEmployee();</span><br><span class="line">            emp.setId(<span class="string">&quot;学院员工id &quot;</span> + i);</span><br><span class="line">            list.add(emp);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> list;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">printCollegeEmployee</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        List&lt;CollegeEmployee&gt; list1 = <span class="keyword">this</span>.getAllEmployee();</span><br><span class="line">        System.out.println(<span class="string">&quot;---学院员工----&quot;</span>);</span><br><span class="line">        <span class="keyword">for</span> (CollegeEmployee e : list1) &#123;</span><br><span class="line">            System.out.println(e.getId());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//学校总部员工类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SchoolEmployee</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String id;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(String id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//学校管理类</span></span><br><span class="line"><span class="comment">//TODO 直接朋友 Employee CollegeManager</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SchoolManager</span> </span>&#123;</span><br><span class="line">    <span class="comment">//返回学校总部的员工</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;SchoolEmployee&gt; <span class="title">getAllEmployee</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        List&lt;SchoolEmployee&gt; list = <span class="keyword">new</span> ArrayList&lt;SchoolEmployee&gt;();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123; <span class="comment">//这里我们增加了5个员工到list</span></span><br><span class="line">            SchoolEmployee emp = <span class="keyword">new</span> SchoolEmployee();</span><br><span class="line">            emp.setId(<span class="string">&quot;学校总部员工id= &quot;</span> + i);</span><br><span class="line">            list.add(emp);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> list;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//该方法完成输出学校总部和学院员工信息(id)</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">printAllEmployee</span><span class="params">(CollegeManager sub)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//获取到学院员工</span></span><br><span class="line">        <span class="comment">//TODO 非直接朋友 CollegeEmployee  应该提取到  CollegeManager</span></span><br><span class="line"><span class="comment">//        List&lt;CollegeEmployee&gt; list1 = sub.getAllEmployee();</span></span><br><span class="line"><span class="comment">//        System.out.println(&quot;---学院员工----&quot;);</span></span><br><span class="line"><span class="comment">//        for (CollegeEmployee e : list1) &#123;</span></span><br><span class="line"><span class="comment">//            System.out.println(e.getId());</span></span><br><span class="line"><span class="comment">//        &#125;</span></span><br><span class="line">        sub.printCollegeEmployee();<span class="comment">//只提供方法，不把具体实现放在其他类里面。</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取到学校总部员工</span></span><br><span class="line">        List&lt;SchoolEmployee&gt; list2 = <span class="keyword">this</span>.getAllEmployee();</span><br><span class="line">        System.out.println(<span class="string">&quot;------学校总部员工------&quot;</span>);</span><br><span class="line">        <span class="keyword">for</span> (SchoolEmployee e : list2) &#123;</span><br><span class="line">            System.out.println(e.getId());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> <strong>==快速记忆：只与直接的朋友通信。校长管老师，老师管学生。校长找学生不会直接去找，而是通过老师去找。==</strong></p>
</li>
</ol>
<h2 id="7）、合成复用原则（Composite-Reuse）"><a href="#7）、合成复用原则（Composite-Reuse）" class="headerlink" title="7）、合成复用原则（Composite Reuse）"></a>7）、合成复用原则（Composite Reuse）</h2><p><strong>目的：</strong>防止类的体系庞大</p>
<ol>
<li>找出应用中可能需要变化之处，把它们独立出来，不要和那些不需要变化的代码混在一起。</li>
<li>针对接口编程，而不是针对实现编程。</li>
<li>为了交互对象之间的松耦合设计而努力。</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CompositeReuse</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;------依赖------&quot;</span>);</span><br><span class="line">        B b = <span class="keyword">new</span> B();</span><br><span class="line">        b.Operation1(<span class="keyword">new</span> A());</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;------聚合------&quot;</span>);</span><br><span class="line">        b.setA(<span class="keyword">new</span> A());</span><br><span class="line">        b.Operation2();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;------组合------&quot;</span>);</span><br><span class="line">        b.Operation3();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Operation1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;A Operation1&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Operation2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;A Operation2&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Operation3</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;A Operation3&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//如果只是需要用到 A类的方法，尽量不要使用继承。而是使用，依赖，聚合，组合的方式</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Operation1</span><span class="params">(A a)</span> </span>&#123;<span class="comment">//TODO 依赖</span></span><br><span class="line">        a.Operation1();</span><br><span class="line">        a.Operation2();</span><br><span class="line">        a.Operation3();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//==============================================================</span></span><br><span class="line">    A a;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setA</span><span class="params">(A a)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.a = a;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Operation2</span><span class="params">()</span> </span>&#123;<span class="comment">//TODO 聚合</span></span><br><span class="line">        a.Operation1();</span><br><span class="line">        a.Operation2();</span><br><span class="line">        a.Operation3();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//==============================================================</span></span><br><span class="line">    A a1 = <span class="keyword">new</span> A();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Operation3</span><span class="params">()</span> </span>&#123;<span class="comment">//TODO 组合</span></span><br><span class="line">        a1.Operation1();</span><br><span class="line">        a1.Operation2();</span><br><span class="line">        a1.Operation3();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>==快速记忆：当类与类之间的关系是”Is-A”时，用继承；当类与类之间的关系是”Has-A”时，用组合。==</strong></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">方陈勇</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://fangchenyong.top/2020/07/13/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E4%B8%83%E5%A4%A7%E5%8E%9F%E5%88%99/">http://fangchenyong.top/2020/07/13/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E4%B8%83%E5%A4%A7%E5%8E%9F%E5%88%99/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://fangchenyong.top" target="_blank">Joey</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a><a class="post-meta__tags" href="/tags/%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99/">设计原则</a></div><div class="post_share"><div class="social-share" data-image="https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/BEF238F4E59CF4D91A694FE9C5DBC030.JPG" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/07/13/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E5%88%9B%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F-%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/"><img class="prev-cover" src="https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/BEF238F4E59CF4D91A694FE9C5DBC030.JPG" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">设计模式-创建型模式-单例模式</div></div></a></div><div class="next-post pull-right"><a href="/2020/04/19/%E6%95%B0%E6%8D%AE%E5%BA%93-MySQL-MySQL%E9%AB%98%E7%BA%A7/"><img class="next-cover" src="https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/BEF238F4E59CF4D91A694FE9C5DBC030.JPG" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">MySQL高级</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2020/07/13/设计模式-创建型模式-单例模式/" title="设计模式-创建型模式-单例模式"><img class="cover" src="https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/BEF238F4E59CF4D91A694FE9C5DBC030.JPG" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-07-13</div><div class="title">设计模式-创建型模式-单例模式</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/3FD9B055-6361-49B7-B8CE-5BA9144BD27F.JPG" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">方陈勇</div><div class="author-info__description">一路向前</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">40</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">47</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">49</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/fangchenyong"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/fangchenyong" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:1013659102@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">个人笔记，如有疑问请联系 QQ:1013659102。</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E4%B8%83%E5%A4%A7%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99"><span class="toc-text">设计模式-七大设计原则</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%EF%BC%89%E3%80%81%E5%8D%95%E4%B8%80%E8%81%8C%E8%B4%A3%E5%8E%9F%E5%88%99%EF%BC%88Single-Responsibility%EF%BC%89"><span class="toc-text">1）、单一职责原则（Single Responsibility）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%EF%BC%89%E3%80%81%E6%8E%A5%E5%8F%A3%E9%9A%94%E7%A6%BB%E5%8E%9F%E5%88%99%EF%BC%88Interface-Segregation%EF%BC%89"><span class="toc-text">2）、接口隔离原则（Interface Segregation）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%EF%BC%89%E3%80%81%E4%BE%9D%E8%B5%96%E5%80%92%E8%BD%AC%E5%8E%9F%E5%88%99%EF%BC%88Dependence-Inversion%EF%BC%89"><span class="toc-text">3）、依赖倒转原则（Dependence Inversion）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%EF%BC%89%E3%80%81%E9%87%8C%E6%B0%8F%E6%9B%BF%E6%8D%A2%E5%8E%9F%E5%88%99%EF%BC%88Liskov-Substitution%EF%BC%89"><span class="toc-text">4）、里氏替换原则（Liskov Substitution）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5%EF%BC%89%E3%80%81%E5%BC%80%E9%97%AD%E5%8E%9F%E5%88%99%EF%BC%88Open-Closed%EF%BC%89"><span class="toc-text">5）、开闭原则（Open Closed）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6%EF%BC%89%E3%80%81%E8%BF%AA%E7%B1%B3%E7%89%B9%E6%B3%95%E5%88%99%EF%BC%88Demeter%EF%BC%89"><span class="toc-text">6）、迪米特法则（Demeter）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7%EF%BC%89%E3%80%81%E5%90%88%E6%88%90%E5%A4%8D%E7%94%A8%E5%8E%9F%E5%88%99%EF%BC%88Composite-Reuse%EF%BC%89"><span class="toc-text">7）、合成复用原则（Composite Reuse）</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/03/21/%E9%9D%A2%E8%AF%95-%E5%B9%B6%E5%8F%91%E3%80%81%E5%A4%9A%E7%BA%BF%E7%A8%8B/" title="面试题-并发编程"><img src="https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/BEF238F4E59CF4D91A694FE9C5DBC030.JPG" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="面试题-并发编程"/></a><div class="content"><a class="title" href="/2021/03/21/%E9%9D%A2%E8%AF%95-%E5%B9%B6%E5%8F%91%E3%80%81%E5%A4%9A%E7%BA%BF%E7%A8%8B/" title="面试题-并发编程">面试题-并发编程</a><time datetime="2021-03-20T16:00:00.000Z" title="发表于 2021-03-21 00:00:00">2021-03-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/03/20/%E9%9D%A2%E8%AF%95-%E9%9B%86%E5%90%88/" title="面试题-集合框架"><img src="https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/BEF238F4E59CF4D91A694FE9C5DBC030.JPG" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="面试题-集合框架"/></a><div class="content"><a class="title" href="/2021/03/20/%E9%9D%A2%E8%AF%95-%E9%9B%86%E5%90%88/" title="面试题-集合框架">面试题-集合框架</a><time datetime="2021-03-19T16:00:00.000Z" title="发表于 2021-03-20 00:00:00">2021-03-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/03/20/Java-%E6%BA%90%E7%A0%81-JDK8-HashMap/" title="JDK8 HashMap源码"><img src="https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/BEF238F4E59CF4D91A694FE9C5DBC030.JPG" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JDK8 HashMap源码"/></a><div class="content"><a class="title" href="/2021/03/20/Java-%E6%BA%90%E7%A0%81-JDK8-HashMap/" title="JDK8 HashMap源码">JDK8 HashMap源码</a><time datetime="2021-03-19T16:00:00.000Z" title="发表于 2021-03-20 00:00:00">2021-03-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/03/13/The%20Road%20To%20Bald%20Man!/" title="The Road To Bald Man!"><img src="https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/BEF238F4E59CF4D91A694FE9C5DBC030.JPG" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="The Road To Bald Man!"/></a><div class="content"><a class="title" href="/2021/03/13/The%20Road%20To%20Bald%20Man!/" title="The Road To Bald Man!">The Road To Bald Man!</a><time datetime="2021-03-12T16:00:00.000Z" title="发表于 2021-03-13 00:00:00">2021-03-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2020/07/21/%E6%A1%86%E6%9E%B6-Maven-%E9%85%8D%E7%BD%AE%E6%A0%87%E7%AD%BE%E8%AF%A6%E8%A7%A3/" title="Maven配置标签详解"><img src="https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/BEF238F4E59CF4D91A694FE9C5DBC030.JPG" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Maven配置标签详解"/></a><div class="content"><a class="title" href="/2020/07/21/%E6%A1%86%E6%9E%B6-Maven-%E9%85%8D%E7%BD%AE%E6%A0%87%E7%AD%BE%E8%AF%A6%E8%A7%A3/" title="Maven配置标签详解">Maven配置标签详解</a><time datetime="2020-07-20T16:00:00.000Z" title="发表于 2020-07-21 00:00:00">2020-07-21</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://fangchenyong.oss-cn-hangzhou.aliyuncs.com/BEF238F4E59CF4D91A694FE9C5DBC030.JPG')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2021 By 方陈勇</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">人生没有退路！</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script></div></body></html>